<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
      }
      .container {
        width: 400px;
        height: 400px;
        background-color: lightpink;
        margin: 20px auto;
        text-align: center;
      }
      .div {
        width: 100px;
        height: 100px;
        background-color: lightblue;
      }
    </style>
  </head>
  <body>
    <div class="container">
      <button class="button">点我</button>
      <div class="div"></div>
    </div>

    <script>
      const button = document.querySelector('.button')
      const container = document.querySelector('.container')
      const div = document.querySelector('.div')

      const mutationObserver = new MutationObserver(mutations => {
        console.log(mutations)
        mutations.forEach(mutation => {
          mutation.addedNodes.forEach(node => {
            if (node.nodeName === 'DIV') {
              console.log('div被添加了')
            }
          })
          mutation.removedNodes.forEach(node => {
            if (node.nodeName === 'DIV') {
              console.log('div被移除了')
            }
          })
        })
      })
      mutationObserver.observe(container, { childList: true })

      let flag = container.contains(div)
      button.addEventListener('click', () => {
        if (flag) {
          container.removeChild(div)
        } else {
          container.appendChild(div)
        }
        flag = !flag
      })
    </script>
  </body>
</html>
